// @ts-ignore
import { getUserInfo } from '../../http/api/userServiceApi'
import { getOrderById, realTimeLocationUpload } from '../../http/api/orderService'
import { getDistant } from '../../http/api/positionApi'
import { formatTime } from '../../utils/util'

let moment = require('../../utils/moment')
let amapFile = require('../../lib/amap-wx.130')
// @ts-ignore
let config = require('../../lib/config')
Page({
    /**
     * 页面的初始数据
     */
    data: {
        userLocation: {
            lat: '',
            lng: '',
            address: ''
        },
        orderId: '',
        orderInfo: {},
        orderType: '',
        markers: [
            {
                iconPath: '',
                id: 0,
                latitude: 0,
                longitude: 0,
                width: 32,
                height: 32
            }
        ],
        distance: '',
        duration: '',
        cost: '',
        polyline: []
    } as any,

    async calculateTime() {
        const data: any = await getDistant(this.data.orderInfo.start_address, this.data.orderInfo.end_address)
        console.log(formatTime(data[0].duration), '----calculateTime')

        this.setData({
            duration: formatTime(data[0].duration)
        })
    },

    call(e: any) {
        console.log(e.currentTarget.dataset.phone)
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.phone //仅为示例，并非真实的电话号码
        })
    },

    //生成唯一不重复ID
    generateUuid: function () {
        // 生成随机数
        const randomNum = Math.floor(Math.random() * 1000000)

        // 获取当前时间戳
        const timestamp = Date.now()

        // 拼接随机数和时间戳
        return randomNum + timestamp
    },

    setOwnerLocation() {
        let that = this
        let myAmapFun = new amapFile.AMapWX({ key: config.Config.key })
        //获取自己所在地址的定位
        myAmapFun.getRegeo({
            success: function (data: any) {
                //成功回调
                console.log(data, 'getRegeo')
                const { longitude, latitude, name } = data[0]
                const { markers, orderInfo } = that.data

                markers[0] = {
                    iconPath: orderInfo.user_icon,
                    id: 0,
                    latitude,
                    longitude,
                    width: 32,
                    height: 32
                }
                that.setData({
                    userLocation: {
                        lat: latitude,
                        lng: longitude,
                        address: name
                    },
                    markers: markers
                })
            },
            fail: function (info: any) {
                //失败回调
                console.log(info)
            }
        })
    },

    async connect() {
        console.log(wx.getStorageSync('isConnectWS'), "---wx.getStorageSync('isConnectWS')")
        if (!wx.getStorageSync('isConnectWS')) {
            await wx.connectSocket({
                url: 'wss://api.myscw.top:8085/'
            })
            wx.setStorageSync('isConnectWS', true)
            wx.getStorageSync('timer') && clearInterval(wx.getStorageSync('timer'))
            const timer = setInterval(async () => {
                await realTimeLocationUpload(this.data.userLocation)
            }, 5 * 60 * 1000)
            wx.setStorageSync('timer', timer)
        } else {
            console.warn('已存在ws连接')
        }
    },

    login(userId: any, orderId: any) {
        console.log(
            JSON.stringify({
                type: 'login',
                login_type: 'user',
                user: userId,
                order_id: orderId
            })
        )
        // 注册
        wx.sendSocketMessage({
            data: JSON.stringify({
                type: 'login',
                login_type: 'user',
                user: userId,
                order_id: orderId
            }), //这里根据后台的格式发送数据，好像这个需要转换成字符串。
            success: (res: any) => {
                console.log('消息发送成功,登录成功', res)
            },
            fail: async res => {
                console.log('消息发送失败,登录失败', res)
                // 关闭ws连接
                this.reconnect(userId, orderId)
            }
        })
    },

    openConnect() {
        wx.onSocketOpen(function (res: any) {
            console.log(res, 'WebSocket连接已打开！')
        })
    },

    async reconnect(userId: string, orderId: string) {
        await wx.removeStorageSync('isConnectWS')
        setTimeout(async () => {
            // 连接ws
            await this.connect()
            // 打开连接
            await this.openConnect()
            await this.login(userId, orderId)
        }, 2000)
    },

    getMessage() {
        let that = this
        let flag = true

        wx.onSocketMessage(async function (res: any) {
            let resValue = JSON.parse(res.data)
            console.log('服务器发送的消息：', resValue)
            if (resValue.type == 'order_driver_location' && resValue.data) {
                if (flag) {
                    // 有司机接单
                    const openid = await wx.getStorageSync('openid')
                    const resOrder: any = await getOrderById(openid, that.data.orderInfo.ID)
                    console.log(resOrder, '---有司机接单resOrder')
                    const orderInfo = resOrder[0]
                    that.setData({
                        orderInfo
                    })
                }
                // 有司机
                const { markers, orderInfo } = that.data
                if (resValue.data) {
                    console.log('有司机信息', resValue.data)
                    // 设置位置
                    markers[1] = {
                        iconPath: orderInfo.duser_icon,
                        id: 1,
                        latitude: resValue.data.lat,
                        longitude: resValue.data.lng,
                        width: 32,
                        height: 32
                    }
                    that.setData({
                        markers: markers
                    })
                    if (resValue.data.order_type == 3) {
                        // 已取货 不再上报位置
                        await clearInterval(wx.getStorageSync('timer'))
                        await wx.removeStorageSync('timer')
                    }
                    if (resValue.data.order_type == 4 || resValue.data.order_type == 5) {
                        console.log('订单完成')

                        // 关闭ws连接
                        await wx.closeSocket()
                        await wx.removeStorageSync('openLocationBackground')
                        await wx.removeStorageSync('isConnectWS')
                        await wx.removeStorageSync('userWsID')
                        wx.stopLocationUpdate({
                            success: function () {
                                console.log('停止后台定位成功')
                            },
                            fail: function (res) {
                                console.error('停止后台定位失败', res)
                            }
                        })
                    }
                    that.setData({
                        orderType: config.Config.ORDER_MAP[resValue.data.order_type]
                    })
                    flag = false
                }
            }
        })
        wx.onSocketError(function (err) {
            console.error('WebSocket 连接出错', err)

            that.reconnect(that.createUser(), that.data.orderInfo.ID)
        })
        wx.onSocketClose(function (res) {
            console.log('WebSocket 连接已关闭', res)
            // 在这里可以处理连接关闭后的逻辑
        })
    },

    sendMessage() {
        let that = this

        if (!wx.getStorageSync('openLocationBackground')) {
            wx.authorize({
                scope: 'scope.userLocationBackground',
                success: (res: any) => {
                    console.log('有权限', res)
                    wx.startLocationUpdateBackground({
                        type: 'gcj02', //传参类型可以根据需求设置
                        success: (res: any) => {
                            console.log('获取位置成功', res)
                            wx.setStorageSync('openLocationBackground', true)
                            wx.onLocationChange(async data => {
                                console.log(data, 'onLocationChange')
                                const { latitude, longitude } = data
                                const { markers, orderInfo } = that.data

                                markers[0] = {
                                    iconPath: orderInfo.user_icon,
                                    id: 0,
                                    latitude,
                                    longitude,
                                    width: 32,
                                    height: 32
                                }
                                that.setData({
                                    longitude,
                                    latitude,
                                    location: '',
                                    userLocation: {
                                        lat: latitude,
                                        lng: longitude,
                                        address: ''
                                    },
                                    markers: markers
                                })
                                console.log(
                                    JSON.stringify({
                                        //
                                        type: 'User_Route_Log_Add',
                                        login_type: 'user',
                                        user: wx.getStorageSync('userWsID'),
                                        order_id: that.data.orderInfo.ID,
                                        lat: latitude,
                                        lng: longitude,
                                        address: ''
                                    }),
                                    '----User_Route_Log_Add'
                                )
                                wx.sendSocketMessage({
                                    data: JSON.stringify({
                                        //
                                        type: 'User_Route_Log_Add',
                                        login_type: 'user',
                                        user: wx.getStorageSync('userWsID'),
                                        order_id: that.data.orderInfo.ID,
                                        lat: latitude,
                                        lng: longitude,
                                        address: ''
                                    }), //这里根据后台的格式发送数据，好像这个需要转换成字符串。
                                    success: res => {
                                        console.log('消息发送成功', res)
                                    },
                                    fail: res => {
                                        console.log('消息发送失败', res)
                                    }
                                })
                            })
                        },
                        fail: (res: any) => {
                            console.log(res, '----没有权限')
                        }
                    })
                },
                fail: (res: any) => {
                    console.log(res, '----没有权限')
                }
            })
        } else {
            console.warn('已开启后台定位!')
        }
    },

    createUser() {
        if (!wx.getStorageSync('userWsID')) {
            const id = `user_${this.generateUuid()}`
            wx.setStorageSync('userWsID', id)
            return id
        } else {
            return wx.getStorageSync('userWsID')
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options: any) {
        console.log(options, '====options')

        let that = this
        // 获取用户信息
        const orderId = options.orderId
        const openid = wx.getStorageSync('openid')

        const resOrderInfo: any = await getOrderById(openid, options.orderId)
        const orderInfo = resOrderInfo[0]
        console.log(orderInfo, '---resOrder')
        // 设置用户当前位置
        await that.setOwnerLocation()
        this.setData({
            orderInfo: {
                ...orderInfo,
                order_time: moment.formatTime(orderInfo.order_time),
                order_get_time: moment.formatTime(orderInfo.order_get_time)
            },
            orderType: config.Config.ORDER_MAP[orderInfo.order_type]
        })

        this.calculateTime()

        const userId = this.createUser()
        if (orderInfo.order_type == 4 || orderInfo.order_type == 5) {
            await wx.removeStorageSync('isConnectWS')
            await wx.removeStorageSync('userWsID')
            await clearInterval(wx.getStorageSync('timer'))
            await wx.removeStorageSync('timer')
            await wx.closeSocket()
            wx.onSocketClose(function (res: any) {
                console.log(res, 'WebSocket连接已关闭！')
            })
            return
        }
        if (orderInfo.order_type !== 4 || orderInfo.order_type !== 5) {
            console.log(orderInfo, orderId, userId, '---orderInfo')

            // 连接ws
            await this.connect()
            // 打开连接
            await this.openConnect()
            // 获取消息
            await this.getMessage()
            setTimeout(async () => {
                // 登录
                await this.login(userId, this.data.orderInfo.ID)
                // if (!wx.getStorageSync('isConnectWS')) {
                await this.sendMessage()
                // } else {
                //     console.log('已有后台定位！')
                // }
            }, 1000)
        }
    },

    onUnload() {
        // wx.closeSocket()
        // wx.onSocketClose(function (res: any) {
        //     console.log(res, 'WebSocket连接已关闭！')
        // })
    }
})
